<?php

/**
 *查询
$mysqlStmt = new MysqlStmt ();

$query = "select * from user where id =?";
$stmt = $mysqlStmt->stmt;

$result=$stmt->prepare ( $query );
if (! $result) {
	die ( 'sql 语句错误 ' . $stmt->errno . ':' . $stmt->error );
}
$pid = 10;
$stmt->bind_param ( 'i', $pid );
$stmt->bind_result ( $id, $name, $age );

$stmt->execute ();

$stmt->store_result ();

while ( $stmt->fetch () ) {
	echo $id . '---' . $name . '---' . $age . '<br/>';
}
$stmt->free_result ();
 * 
 * 
 * 
 * 更新
 * $mysqlStmt = new MysqlStmt ();

$query = "update  user  set name='千与千寻' where id =?";
$stmt = $mysqlStmt->stmt;

$result=$stmt->prepare ( $query );
if (! $result) {
		die ( 'sql 语句错误 ' . $stmt->errno . ':' . $stmt->error );
}
$pid = 10;
$stmt->bind_param ( 'i', $pid );
$stmt->execute ();

echo $stmt->affected_rows;
echo $stmt->insert_id;
 * 
 * 
 * @author hetf
 *
 */
class MysqlStmt {
	const HOST = 'localhost';
	const USERNAME = 'root';
	const PASSWORD = '123456';
	const DBNAME = 'test';
	const CHARSET = 'utf8';
	private $conn;
	public $stmt;
	
	/**
	 * 构造<br/>
	 * 1.实例化连接<br/>
	 * 2.判断连接错误<br/>
	 * 3.设置字符集<br/>
	 * 4.初始化mysqli_stmt实例<br/>
	 */
	function __construct() {
		
		// 实例化连接
		$this->conn = @ new mysqli ( self::HOST, self::USERNAME, self::PASSWORD, self::DBNAME );
		
		// 连接错误
		if (mysqli_connect_errno ()) {
			die ( mysqli_connect_errno () . ":" . mysqli_connect_error () );
		}
		
		// 设置字符集
		$this->conn->query ( 'set names ' . self::CHARSET );
		
		// 初始化stmt实例
		$this->stmt = $this->conn->stmt_init ();
	}
	
	/**
	 * 析构方法<br/>
	 *
	 * 关闭mysqli_stmt对象<br/>
	 * 关闭mysqli对象<br/>
	 */
	function __destruct() {
		
		// 无连接错误 并无sql错误
		if (! mysqli_connect_errno () && ! $this->stmt->errno) {
			$this->stmt->close ();
		}
		
		// 判断无连接错误 ，如果有连接错误可能对象未创建成功，调用半闭方法出错;
		if (! mysqli_connect_errno ()) {
			$this->conn->close ();
		}
	}
}